package com.ck.controller.teacher;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.ck.domain.Subject;
import com.ck.service.QuestionService;

public class AddNewSubjectController extends SimpleFormController {
	
	private QuestionService questionService;

	public void setQuestionService(QuestionService questionService) {
		this.questionService = questionService;
	}
	
	protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception {
		
		Subject subject = (Subject) command;
		Map model = errors.getModel();
		
		//后台校验
		boolean flag = true;
		String name = subject.getName().trim();
		String remark = subject.getRemark().trim();
		
		if(name == null || "".equals(name)) {
			model.put("error_name", "请输入科目名称");
			flag = false;
		}
		
		if(name.length() > 30) {
			model.put("error_name", "名称长度：1-30个字符");
			flag = false;
		}
		
		if( remark == null || "".equals(remark) ){
			subject.setRemark(null);
        }else{
        	if(remark.length() > 60) {
    			model.put("error_remark", "备注长度：0-60个字符");
    			flag = false;
    		}
        }
		
		//校验不通过
        if(!flag){
        	model.put("name", name);
        	model.put("remark", remark);
			return new ModelAndView(getFormView(), model);
		}
		
		boolean isNewSubject = questionService.addNewSubject(subject, model);
		
		if (isNewSubject) {
            return new ModelAndView(getSuccessView(),model);
        } else {
        	model.put("name", name);
        	model.put("remark", remark);
            return new ModelAndView(getFormView(), model);
        }
	}
}
